import reactive from "./reactive.js";
import { isObejct } from "./utils.js";
import { track, trigger } from "./effect.js";
import { trackTypes, triggerTypes } from "./effectType.js";
const __isRef = Symbol("isRef");
export default function ref(rawValue) {
  return createRef(rawValue, false);
}

export function shallowRef(rawValue) {
  // 浅层代理，只做一层代理
  return createRef(rawValue, true);
}

export function isRef(ref) {
  return !!ref[__isRef];
}

export function unRef(ref) {
  return isRef(ref) ? ref.value : ref;
}

export function createRef(rawValue, shallow = false) {
  // 判断是否是ref，是，直接返回
  if (rawValue[__isRef]) {
    console.log("isRef");
    return rawValue;
  }
  // 判断是否是对象，是，则进行reactive深度代理
  if (isObejct(rawValue) && !shallow) {
    rawValue = reactive(rawValue);
  }
  return {
    [__isRef]: true,
    get value() {
      // 触发依赖收集
      track(this, trackTypes.GET, "value");
      return rawValue;
    },
    set value(newValue) {
      if (newValue !== rawValue) {
        const oldValue = rawValue;
        rawValue = newValue;
        // 触发派发更新
        trigger(this, triggerTypes.SET, "value", newValue, oldValue);
      }
    },
  };
}
